package com.fjwt.gz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjwt.gz.components.mq.model.ExportExcelMQ;
import com.fjwt.gz.components.mq.vender.IMQSender;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.third.util.jilin.RsaFgmUtils;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.dto.FansAuthDTO;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.AgentScoreEntity;
import com.fjwt.gz.db.entity.AgentScoreRuleEntity;
import com.fjwt.gz.db.entity.FansAuthEntity;
import com.fjwt.gz.db.vo.FansAuthVO;
import com.fjwt.gz.service.mapper.FansAuthMapper;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 会员信息基础表（18个地市进行关联） 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class FansAuthService extends ServiceImpl<FansAuthMapper, FansAuthEntity> {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private FansAuthService fansAuthService;
    @Autowired
    private ScoreRecordTotalService scoreRecordTotalService;
    @Autowired
    private AgentScoreService agentScoreService;
    @Autowired
    private AgentScoreRuleService agentScoreRuleService;
    @Autowired
    private SysExportTaskService sysExportTaskService;
    @Autowired
    private IMQSender mqSender;

    public JSONObject instAuis(JSONObject respData, String provinceCode, String locationAgentNo, String appId, Long fansId, JSONObject activityJson) {
        JSONObject respJson = new JSONObject();
        FansAuthEntity fansAuthEntity = new FansAuthEntity();
        activityJson.put("fansId", fansId);
        activityJson.put("appId", appId);
        activityJson.put("locationAgentNo", locationAgentNo);
        if (provinceCode.equals("jilin")) {
            jilinRealNameAuth(respData, respJson, fansAuthEntity, locationAgentNo, fansId, appId, activityJson);
        }else if (provinceCode.equals("henan")) {
            henanRealNameAuth(respData, respJson, fansAuthEntity, locationAgentNo, fansId, appId, activityJson);
        }
        return respJson;
    }

    /**
     * 吉林的实名认证
     * @param respData
     * @param respJson
     * @param fansAuthEntity
     * @param
     * @param fansId
     * @param activityJson
     */
    private void jilinRealNameAuth(JSONObject respData, JSONObject respJson, FansAuthEntity fansAuthEntity, String locationAgentNo, Long fansId, String appId, JSONObject activityJson){
        log.info("实名认证response:{}", respData);
        log.info("实名认证验签前返回数据response:{}", JSONUtil.toJsonStr(respData));
        String code = respData.getString("code");
        if ("200".equals(code)) {
            String data = respData.getString("data");
            fansAuthEntity.setFansId(fansId);
            fansAuthEntity.setAuthRepInfo(respData.getString("data"));
            // 设置客户唯一标识
            String cstmNo;
            try {
                cstmNo = RsaFgmUtils.decryptByPublicKey(RsaFgmUtils.publicKey, data);
                log.info("实名认证唯一id解签cstmNo:{}", cstmNo);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BizException("数据解密失败");
            }
            if (StringUtils.isNullOrEmpty(cstmNo)) {
                throw new BizException("数据解密失败");
            }
            ObjectMapper objectMapper = new ObjectMapper();
            JSONArray decryptlist;
            try {
                decryptlist = objectMapper.readValue(cstmNo, JSONArray.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            cstmNo = decryptlist.getString(0);
            log.info("实名认证唯一id解签cstmNo:{}", cstmNo);
                LambdaQueryWrapper<FansAuthEntity> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FansAuthEntity::getCstmNo, cstmNo);
                List<FansAuthEntity> list = fansAuthService.getBaseMapper().selectList(queryWrapper);
                if (null != list && list.size() > 0) {
                    throw new BizException("您已存在账户完成实名，请勿重复");
                }
            respJson.put("isAuth", "Y");
            fansAuthEntity.setCstmNo(cstmNo);
            fansAuthEntity.setCstmName(activityJson.getString("name"));
            fansAuthEntity.setAuthPhone(activityJson.getString("phone"));//保存实名手机号
            fansAuthEntity.setAgentNo(locationAgentNo);
            fansAuthEntity.setAuthIdCard(activityJson.getString("idcard")); // 实名认证身份证号
            fansAuthEntity.setAuthBankCard(activityJson.getString("bankCard"));//银行卡号
            Date date = new Date();
            fansAuthEntity.setAuthTime(date);
            fansAuthEntity.setCreatedAt(date);
            fansAuthService.save(fansAuthEntity);
            // 获取积分规则 并生成福分
            getScoreRuleAndScoreGenerate(fansId, locationAgentNo, appId, activityJson);
        } else {
            respJson.put("msg", respData.getString("msg"));
            String activityTemplateNo = activityJson.getString("activityTemplateNo");
            Long activityId = activityJson.getLong("activityId");
            respJson.put("isAuth", "N");
            if (isHasCurrentActivity(activityTemplateNo, activityId)) {
                BaseActivityService activityService = SpringBeansUtil.getBean(activityTemplateNo + "Service", BaseActivityService.class);
                activityService.realNameAfter(activityJson);
                respJson.put("dataFlag", "1");//前端用字段
            } else {
                respJson.put("dataFlag", "0");//前端用字段
            }
        }
    }

    /**
     * 河南的实名认证
     * @param respData
     * @param respJson
     * @param fansAuthEntity
     * @param
     * @param fansId
     * @param activityJson
     */
    private void henanRealNameAuth(JSONObject respData, JSONObject respJson, FansAuthEntity fansAuthEntity, String locationAgentNo, Long fansId, String appId, JSONObject activityJson){
        String code = respData.getString("code");
        if ("0000".equals(code)) {
            String data = respData.getString("data");
            JSONObject dataJson = JSONObject.parseObject(data);
            String isAuth = dataJson.getString("isAuth");
            respJson.put("isAuth", isAuth);
            fansAuthEntity.setFansId(fansId);
            JSONObject authRepInfo = JSONObject.parseObject(data);
            fansAuthEntity.setAuthRepInfo(authRepInfo.getString("cardInfo"));
            if ("Y".equals(isAuth)) {
                String cardInfo = dataJson.getString("cardInfo");
                String cstmNo = null;
                String cstmName = activityJson.getString("name");
                // 设置客户唯一标识
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(cardInfo)) {
                    JSONArray array = JSONArray.parseArray(cardInfo);
                    JSONObject object = JSONObject.parseObject(array.getString(0));
                    cstmNo = object.getString("cstmNo");
                    cstmName = object.getString("cstmName");
                    LambdaQueryWrapper<FansAuthEntity> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(FansAuthEntity::getCstmNo, cstmNo);
                    List<FansAuthEntity> list = fansAuthService.getBaseMapper().selectList(queryWrapper);
                    if (ObjectUtil.isNotEmpty(list)) {
                        throw new BizException("您已存在账户完成实名，请勿重复");
                    }
                    fansAuthEntity.setCstmNo(cstmNo);
                    fansAuthEntity.setAuthBankCard(object.getString("cardNo"));
                }
                fansAuthEntity.setCstmNo(cstmNo);
                fansAuthEntity.setCstmName(cstmName);
                fansAuthEntity.setAuthPhone(activityJson.getString("phone"));//保存实名手机号
                fansAuthEntity.setAuthIdCard(activityJson.getString("idcard")); // 实名认证身份证号
                fansAuthEntity.setAgentNo(locationAgentNo);
                fansAuthEntity.setAgentNo1("41022445");
                fansAuthEntity.setAgentNo2("41000122");
                Date date = new Date();
                fansAuthEntity.setAuthTime(date);
                fansAuthEntity.setCreatedAt(date);
                fansAuthService.save(fansAuthEntity);
                log.info("实名认证成功: fansAuthEntity{}", fansAuthEntity);
                // 获取积分规则 并生成福分
                getScoreRuleAndScoreGenerate(fansId, locationAgentNo, appId, activityJson);
            } else {
                respJson.put("msg", dataJson.getString("msg"));
                String activityTemplateNo = activityJson.getString("activityTemplateNo");
                Long activityId = activityJson.getLong("activityId");
                if (isHasCurrentActivity(activityTemplateNo, activityId)) {
                    BaseActivityService activityService = SpringBeansUtil.getBean(activityTemplateNo + "Service", BaseActivityService.class);
                    activityService.realNameAfter(activityJson);
                    respJson.put("dataFlag", "1");//前端用字段
                } else {
                    respJson.put("dataFlag", "0");//前端用字段
                }
            }
        }
    }

    /**
     * 获取积分规则 并生成福分
     * @param fansId
     * @param agentNo
     * @param appId
     * @param activityJson
     */
    private void getScoreRuleAndScoreGenerate(Long fansId, String agentNo, String appId, JSONObject activityJson){
        AgentScoreEntity agentScoreByAgentNo = agentScoreService.getAgentScoreByAgentNo(agentNo);
        LambdaQueryWrapper<AgentScoreRuleEntity> queryWrapper = AgentScoreRuleEntity.gw();
        queryWrapper.eq(AgentScoreRuleEntity::getRuleKey, Constants.POINT.AUTH_KEY);
        queryWrapper.eq(AgentScoreRuleEntity::getAgentScoreId, agentScoreByAgentNo.getAgentScoreId());
        queryWrapper.eq(AgentScoreRuleEntity::getState, 1);
        AgentScoreRuleEntity agentScoreRuleEntity = agentScoreRuleService.getOne(queryWrapper);
        scoreRecordTotalService.scoreRecordGenerate(fansId, agentScoreRuleEntity.getScoreRuleId(), "实名认证获得积分", Constants.SCORE.RULE, activityJson, appId);
    }

    protected boolean isHasCurrentActivity(String activityTemplateNo, Long activityId) {
        LambdaQueryWrapper<ActivityEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ActivityEntity::getActivityTemplateNo, activityTemplateNo);
        queryWrapper.eq(ActivityEntity::getActivityId, activityId);
        queryWrapper.eq(ActivityEntity::getState, 4);
        ActivityEntity one = activityService.getOne(queryWrapper);
        return one == null ? false : true;
    }

    public IPage<FansAuthVO> realNameAuth(IPage iPage,FansAuthDTO fansAuthDTO) {
        return baseMapper.realNameAuth(iPage,fansAuthDTO);
    }

    /**
     * 导出实名报表
     *
     * @param
     * @return
     */
    public ApiRes exportReal(FansAuthDTO fansAuthDTO, com.fjwt.gz.core.entity.SysUser sysUser) {
        // 报表名称
        String fileName = "实名信息数据报表";
        // 添加导出任务记录
        Long exportTaskId = sysExportTaskService.addExportTask(sysUser, fileName, Constants.EXPORT_TASK_ENUM.REQUEST_CODE.REAL,
                Constants.EXPORT_TASK_ENUM.RESOURCE_TYPE.FANS, JSONObject.toJSONString(fansAuthDTO));
        // 发送mq
        mqSender.send(ExportExcelMQ.build(exportTaskId));
        return ApiRes.ok();
    }

}
